package main;

import java.io.File;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner( System.in );
        Main main = new Main();
        while ( true ) {
            main.run( scan );
            System.out.println( "处理完成！是否继续？y/Y" );
            String next = scan.next();
            if( "y".equals( next.toLowerCase() ) ) continue;
            scan.close();
            break;
        }
    }

    private void run(Scanner scan) {
        System.out.println( "替换文件名（格式：文件夹路径 原始名 替换名【eg:C:\\文件夹|old_name|new_name】）" );
        while ( scan.hasNext() ) {
            String next = scan.next();
            String[] sp = next.split( "\\|" );
            if( "exit".equals( next.toLowerCase() ) ) break;
            if( sp.length != 3 ) {
                System.out.println( "格式不正确！" );
                continue;
            }
            File[] fs = new File( sp[ 0 ] ).listFiles();
            if( fs == null || fs.length == 0 ) {
                System.out.println( "文件夹路径不存在！" );
                continue;
            }
            replaceName( fs, sp[ 1 ], sp[ 2 ] );
            break;
        }
    }

    private void replaceName(File[] listFiles, String fromName, String toName) {
        for( File file : listFiles ) {
            String oldPath = file.getAbsolutePath();
            //只替换一次
            String newPath = oldPath.replaceFirst( fromName, toName );
            //跳过不需要重命名的文件
            if( oldPath.equals( newPath ) ) continue;
            boolean result = file.renameTo( new File( newPath ) );
            System.out.println(
                    String.format( "【%s】【%s】 --> 【%s】",
                            result ? "成功" : "失败",
                            oldPath.substring( oldPath.lastIndexOf( File.separator ) + 1 ),
                            newPath.substring( oldPath.lastIndexOf( File.separator ) + 1 )
                    )
            );
        }
    }
}
